package webEMI;

import java.io.IOException;
import java.io.PrintWriter;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/CalcEMI")
public class CalcEMI extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {
	PrintWriter out = response.getWriter();
	long amt = Long.parseLong(request.getParameter("amt"));
	int term = Integer.parseInt(request.getParameter("year"));
	if (amt <= 0) {
	    out.write("negative number");
	    // forward(msg as parameter);
	}
	if (amt > 1000000) {
	    out.write("High amount");
	    // forward(msg as parameter);
	}
	Context ctx = null;
	try {
	    ctx = new InitialContext();
	    ejbEMI.CalcEMI cal = (ejbEMI.CalcEMI) ctx
		    .lookup("myEMIjndi#ejbEMI.CalcEMI");
	    double emi = cal.callEMI(amt, term);
	    out.write("<table align='center'>" + "<tr>"
		    + "<td>Required Loan Amount</td>" + "<td>" + amt + "</td>"
		    + "</tr>" + "<tr>" + "<td>Term of Loan (in years)</td>"
		    + "<td>" + term + "</td>" + "</tr>" + "<tr>"
		    + "<td>EMI</td>" + "<td>" + emi + "</td>" + "</tr>"
		    + "</table>");
	    ctx.close();
	} catch (NamingException e) {
	    out.write(e.toString());
	}
    }

    protected void doPost(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {
	doGet(request, response);
    }
}
